package com.imooc.maokeyang.alllearning.security.filter;

import com.imooc.maokeyang.alllearning.security.jwt.JwtTokenUtils;
import com.imooc.maokeyang.alllearning.security.services.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

public class AuthTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtils jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        String token = parseJwt(request);

        if (token != null && jwtTokenUtil.validateJwtToken(token)) {
            String username = jwtTokenUtil.getUsername(token);
            String role = jwtTokenUtil.getUserRole(token);

            //UserDetails userDetails = userDetailsService.loadUserByUsername(username);
//            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
//                    userDetails, null, userDetails.getAuthorities());
//            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

//            SecurityContextHolder.getContext().setAuthentication(authentication);

            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    username, null, Collections.singleton(new SimpleGrantedAuthority(role)));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        chain.doFilter(request, response);
    }

    /**
     * 请求头部获取token
     *
     * @param request
     * @return
     */
    private String parseJwt(HttpServletRequest request) {
        String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);

        // 截取token前面的Bearer 字符,拿到token
        if (StringUtils.hasText(tokenHeader) && tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
            return tokenHeader.substring(7);
        }

        return null;
    }
}
